'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 任务
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoose = require('mongoose');
var _ = require('lodash');
var dataApi = require('../libs/dataApi');
var taskFactory = require('../libs/taskFactory');
var taskMgr = require('../mgr/taskMgr');
var missionConf = require('../config/missionConf.js');
var constantUtil = require('../util/constantUtil.js');

var _initTaskList = function () {
    var task_list = [];
    dataApi.mission.each(function (task_conf, task_id) {
        if (!task_conf.need_id) {
            task_list.push(+task_id);
        }
    });
    return task_list;
};

/**
 * 任务
 */
var taskSchema = new mongoose.Schema({
    // 玩家id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 当前任务列表
    current_task_list: {
        type: Array,
        default: _initTaskList
    },

    // 已经完成的任务列表
    complete_task_list: [Number],

    // 统计的列表
    static_list: {
        type: mongoose.Schema.Types.Mixed,
        default: {}
    }
});

taskSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 获取当前的任务
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
taskSchema.methods.isHaveTask = function (task_id) {
    task_id = +task_id;
    return _.indexOf(this.current_task_list, task_id) !== -1;
};

/**
 * 判断任务是否完成
 * @param  {[type]}  task_id [description]
 * @return {Boolean}         [description]
 */
taskSchema.methods.isTaskComplete = function (task_id) {
    task_id = +task_id;
    return _.indexOf(this.complete_task_list, task_id) !== -1;
};

/**
 * 是否任务能够完成
 * @param  {[type]}  task_id [description]
 * @return {Boolean}         [description]
 */
taskSchema.methods.isTaskCanComplete = function (task_id) {
    task_id = +task_id;
    var now_value = _getTaskProgress(this.static_list, task_id);
    if (!this.isHaveTask(task_id)) {
        return false;
    }
    return now_value >= _getTaskTotalProgress(task_id);
};

/**
 * 移除任务
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
taskSchema.methods.removeTask = function (task_id) {
    // 移除任务
    this.current_task_list.pull(task_id);
};

/**
 * 获取当前的任务列表
 * @return {[type]} [description]
 */
taskSchema.methods.getCurrentTaskList = function () {
    return this.current_task_list;
};

/**
 * 获取任务的奖励
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
taskSchema.methods.rewardTask = function (task_id) {
    task_id = +task_id;
    if (!this.isTaskCanComplete(task_id)) {
        return false;
    }

    // 移除任务
    this.current_task_list.pull(task_id);

    // 添加到reward的列表中
    this.complete_task_list.push(task_id);

    // 刷新后置的任务
    this.refreshFollowTask();
    return true;
};

/**
 * 刷新任务
 * @return {[type]} [description]
 */
taskSchema.methods.refreshFollowTask = function () {
    var self = this;
    dataApi.mission.each(function (task_conf, task_id) {
        var pre_task_id = task_conf.need_id;
        if (!!self.isTaskComplete(pre_task_id)) {
            self.addTask(task_id);
        }
    });
};

/**
 * 添加一个新任务
 * @param {[type]} task_id [description]
 */
taskSchema.methods.addTask = function (task_id) {
    task_id = +task_id;

    // 如果已经完成不加入
    if (!!this.isTaskComplete(task_id)) {
        return false;
    }

    var task = this.isHaveTask(task_id);
    if (!!task) {
        return false;
    }
    this.current_task_list.push(task_id);
    return true;
};

/**
 * 获取统计的列表
 */
taskSchema.methods.getStaticList = function (task_static_type) {
    this.static_list[task_static_type] = this.static_list[task_static_type] || {};
    return this.static_list[task_static_type];
};

taskSchema.methods.setChange = function () {
    this.markModified('static_list');
};

/**
 * 获取修改
 * @return {[type]} [description]
 */
taskSchema.methods.getLastChange = function () {
    return this.toJSON();
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
taskSchema.methods.push = function () {
    this.pushModify();
};

taskSchema.methods.pushModify = function () {
    taskMgr.sendTaskChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send task message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

/**
 * 获取任务的进度
 * @param  {[type]} static_list [description]
 * @param  {[type]} task_id     [description]
 * @return {[type]}             [description]
 */
var _getTaskProgress = function (static_list, task_id) {
    static_list = static_list || {};
    var task_conf = dataApi.mission.findById(task_id);
    if (!task_conf) {
        console.error('task is can not found:' + task_id);
        return 0;
    }

    var task_type = task_conf.type;
    if (!!static_list[task_type]) {
        return taskFactory.getInstance(task_type).getProgress(static_list[task_type], task_conf);
    }
    return 0;
};

/**
 * 获取任务的总进度
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
var _getTaskTotalProgress = function (task_id) {
    var task_conf = dataApi.mission.findById(task_id);
    if (!task_conf) {
        return 999;
    }
    return task_conf.value;
};
/*jslint browser: true, plusplus: true */
var _getTaskList = function (i, task_list) {

    // 先排列出已完成任务如果没有 排优先级最高的任务
    var now_task_list = [];
    // var isVail = false;

    // _.some(task_list, function (value) {
    //     if (value.classify == i) {
    //         if (value.progress >= value.total_progress) {
    //             now_task_list.push(value);
    //             isVail = true;
    //             return true;
    //         }
    //     }
    // });

    // if (!isVail) {
    //     _.some(_.sortBy(task_list, 'classify'), function (value) {
    //         if (value.classify == i) {
    //             now_task_list.push(value);
    //             return true;
    //         }
    //     });
    // }
    _.some(task_list, function (value) {
        if (value.classify == i) {
            now_task_list.push(value);
        }
    });
    var priority_max_item = _.sortBy(now_task_list, 'classify');
    return priority_max_item[priority_max_item.length - 1] || {};
};

if (!taskSchema.options.toJSON) {
    taskSchema.options.toJSON = {};
}
/* jshint unused:false */
taskSchema.options.toJSON.transform = function (doc, ret) {
    // 处理任务进度
    var task_list = [];
    _.each(ret.current_task_list, function (task_id) {
        var mission_conf = missionConf.getMissionConf(task_id);
        if (!mission_conf) {
            console.error('task_id error:', task_id);
            mission_conf = {
                classify: 999999,
                priority: 999999
            };
        }
        task_list.push({
            task_id: task_id,
            progress: _getTaskProgress(ret.static_list, task_id),
            total_progress: _getTaskTotalProgress(task_id),
            classify: mission_conf.classify,
            priority: mission_conf.priority
        });
    });

    var now_task_list1 = [];
    var num = constantUtil.value('mission_type_num');

    for (var i = 1; i < num + 1; i++) {
        var item = _getTaskList(i, task_list);
        now_task_list1.push(item);
    }

    ret.current_task_list = now_task_list1;
    delete ret.role_id;
    delete ret.static_list;
    delete ret._id;
    delete ret.__v;
};

mongoose.model('Task', taskSchema);
